package com.mingtu.guards.activity;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.callback.StringDialogCallback;
import com.hjq.gson.factory.GsonFactory;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.UIUtils;
import com.mingtu.common.view.ContainsEmojiEditText;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.ContactsDepAdapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.ContactsDeptBean;
import com.mingtu.guards.utils.MyConstant;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.mingtu.guards.utils.MyConstant.animationType;
import static com.mingtu.guards.utils.MyConstant.isFirstOnly;
import static com.mingtu.guards.utils.MyConstant.isOpenLoadAnimation;

public class ContactsActivity extends MyBaseActivity {


    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.srl_up)
    SmartRefreshLayout srlUp;
    @BindView(R.id.edit_search)
    ContainsEmojiEditText editSearch;
    @BindView(R.id.tv_search)
    TextView tvSearch;

    private ContactsDepAdapter contactsDepAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_contacts;
    }

    @Override
    protected void initView() {
        setModuleTitle("通讯录");
        super.initView();
    }

    @Override
    protected void initData() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
        recycler.setLayoutManager(linearLayoutManager);
//        recycler.addItemDecoration(new CustomDecoration(context, CustomDecoration.VERTICAL_LIST, R.drawable.shape_dive_line, 0));
        recycler.addItemDecoration(new BottomSpaceItemDecoration());

        contactsDepAdapter = new ContactsDepAdapter();
        if (isOpenLoadAnimation) {
            contactsDepAdapter.isFirstOnly(isFirstOnly);
            contactsDepAdapter.openLoadAnimation(animationType);
        }
        contactsDepAdapter.setEmptyView(new EmptyDataLayout(context));
        recycler.setAdapter(contactsDepAdapter);
        contactsDepAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ContactsDeptBean.ListBean bean = contactsDepAdapter.getData().get(position);
                String deptId = bean.getDeptId();
                String deptName = bean.getName();
                Bundle bundle = new Bundle();
                bundle.putString("deptId", deptId);
                bundle.putString("deptName", deptName);
                IntentUtils.getInstance().readyGo(ContactsActivity.this, ContactsPeopleListActivity.class, bundle);
            }
        });

        editSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH || i == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    search();
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    protected void getData() {
        getDeptData();
        initListener();
    }

    private void initListener() {
        initPullRefresh();//刷新
    }

    private void initPullRefresh() {
        srlUp.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
        srlUp.setEnableLoadMore(false);
        srlUp.setEnableOverScrollDrag(true);
        srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srlUp.finishRefresh(Constant.REFRESH_TIME);
                srlUp.setNoMoreData(false);
                getDeptData();
            }
        });
    }

    /**
     * 获取部门
     */
    private void getDeptData() {
        OkGo.<String>post(MyConstant.POST_CONTACTS_DEPT)
                .tag(this)
                .upJson("")
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            List<ContactsDeptBean.ListBean> dataBeans = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                ContactsDeptBean contactsDeptBean = new ContactsDeptBean();
                                contactsDeptBean = gson.fromJson(result, ContactsDeptBean.class);
                                dataBeans = contactsDeptBean.getList();

                                try {
                                    if (dataBeans != null) {
                                        //请求时先清空数组，防止下拉操作的时候加载重复数据
                                        contactsDepAdapter.getData().clear();
                                        contactsDepAdapter.addData(dataBeans);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));
                            }


                        }
                    }
                });
    }


    @OnClick(R.id.tv_search)
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.tv_search:
                search();
                break;
        }
    }

    /**
     * 搜索
     */
    private void search() {
        String searchKey = UIUtils.getEditText(editSearch);
        if (StringUtils.isEmpty(searchKey)) {
            ToastUtils.showLong("请输入人员名称！");
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString("searchKey", searchKey);
        IntentUtils.getInstance().readyGo(ContactsActivity.this, ContactsSearchListActivity.class, bundle);
    }

}